package com.cskaoyan.service;

import com.cskaoyan.bean.baseresultVO.BaseData;
import com.cskaoyan.bean.baseresultVO.BaseParam;
import com.cskaoyan.bean.domain.Admin;
import com.cskaoyan.mapper.AdminMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


/**
 * @User: Yr
 * @ClassName: AdminServiceImpl
 * @Description:
 */

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    AdminMapper adminMapper;

    /**
     * 按条件查询adminList
     */
    @Override
    public BaseData list(String username, BaseParam baseParam) {

        //开启分页
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        //获取指定数据
        List<Admin> adminList = adminMapper.selectByUsernameOrderBySort(username, baseParam.getSort(), baseParam.getOrder());
        //获取分页信息
        PageInfo pageInfo = new PageInfo(adminList);
        BaseData baseData = BaseData.list(adminList, pageInfo.getTotal());
        baseData.setPage(pageInfo.getPageNum());
        baseData.setPages(pageInfo.getPages());
        baseData.setLimit(baseParam.getLimit());
        return baseData;

    }

    /**
     * 逻辑删除admin
     */
    @Override
    public int delete(Admin admin) {
        admin.setUpdateTime(new Date());
        admin.setDeleted(true);
        return adminMapper.updateByPrimaryKeySelective(admin);
    }

    /**
     * 新增admin
     */
    @Override
    public Admin create(Admin admin) {
        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        try {
            adminMapper.insertSelective(admin);
            return admin;
        } catch (Exception e) {
            throw new DuplicateKeyException("管理员已存在");
        }
    }

    @Override
    public Admin update(Admin admin) {
        admin.setUpdateTime(new Date());
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
            Admin resultAdmin = adminMapper.selectByPrimaryKey(admin.getId());
            admin.setPassword(null);
            admin.setAddTime(resultAdmin.getAddTime());
            return admin;
        }catch (Exception e){
            throw new DuplicateKeyException("管理员已存在");
        }
    }
}
